package cs4280.ass2.filter;

import java.io.IOException;

import javax.servlet.Filter;
import javax.servlet.FilterChain;
import javax.servlet.FilterConfig;
import javax.servlet.ServletException;
import javax.servlet.ServletRequest;
import javax.servlet.ServletResponse;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.apache.log4j.Logger;

import cs4280.ass2.entity.User;

public class AccessControlFilter implements Filter {
	private static final Logger logger = Logger.getLogger(AccessControlFilter.class);

	@Override
	public void init(FilterConfig filterConfig) throws ServletException {

	}

	@Override
	public void doFilter(ServletRequest request, ServletResponse response, FilterChain chain) throws IOException,
	ServletException {
		HttpServletRequest req = (HttpServletRequest) request;
		HttpServletResponse resp = (HttpServletResponse) response;

		User user = (User) req.getSession().getAttribute("loggedInUser");
		if (user == null) {
			logger.info("IP:"+req.getRemoteAddr()+" trying to access protected area without logged in, redirect to login page.");
			resp.sendRedirect(req.getContextPath() + "/login.jsp");
			return;
		}
		chain.doFilter(req, resp);
	}

	@Override
	public void destroy() {
	}

}
